<?php
// 回调注册

namespace JyWxThird\Init\Call;

use JyWxThird\BasicService\Common;
use JyWxThird\Kernel\Http;
use JyWxThird\Kernel\XML;
use JyWxThird\ReplyMsg\ReplyMsg;

class _ServiceProvider extends Common
{
  private $message = null;
  
  /**
   * 注册回调
   *
   * @param        $call
   * @param null   $MsgType 要注册的消息类型，默认为不限
   * @param string $xmlData 微信发过来的xml数据，可空，默认将直拦获取 file_get_contents("php://input")
   * @return false|void
   */
  public function push($call, $MsgType = null, $xmlData = '')
  {
    if (!$this->message) {
      $message = $xmlData ?: file_get_contents("php://input");
      if (!$this->message = XML::parse($message)) {
        echo '消息解析失败，消息内容：' . $message;
        return false;
      }
    }
    
    // 指定消息类型 && 用户操作回调消息
    if ($MsgType && isset($this->message['MsgType'])) {
      // 如：event.CLICK
      if (strpos($MsgType, '.')) {
        [$MsgType, $Event] = explode('.', $MsgType);
        if ($this->message['MsgType'] == $MsgType && $this->message['Event'] == $Event) {
          $call($this->message, $_GET, new ReplyMsg($this->message));
        }
        
      } else if ($this->message['MsgType'] == $MsgType) {
        $call($this->message, $_GET, new ReplyMsg($this->message));
      }
      
      // 支付回调
    } else if (isset($this->message['mch_id']) && isset($this->message['appid'])) {
      if ($MsgType !== 'pay') {
        return false;
      }
      if ($call($this->message, $_GET, new ReplyMsg($this->message))) {
        exit('SUCCESS');
      } else {
        exit('FAIL');
      }
      
    } else {
      $call($this->message, $_GET, new ReplyMsg($this->message));
    }
  }
}
